/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.niedziela12.pai.ejb.user.managers;

import com.niedziela12.pai.ejb.dto.RoleDTO;
import com.niedziela12.pai.ejb.dto.UserDTO;
import com.niedziela12.pai.ejb.dto.UserRolesDTO;
import com.niedziela12.pai.ejb.entities.Role;
import com.niedziela12.pai.ejb.entities.User;
import com.niedziela12.pai.ejb.entities.UserRoles;
import com.niedziela12.pai.ejb.user.facades.UserFacadeLocal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author Kamil
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public class UserManager implements UserManagerLocal {

    @EJB
    private UserFacadeLocal userFacade;

    @Override
    public void addNewUser(UserDTO user) {
        userFacade.create(user.toUser());
    }

    @Override
    public void updateUserInfo(UserDTO user) {
        userFacade.edit(user.toUser());
    }

    @Override
    public void deleteUser(UserDTO user) {
        userFacade.remove(user.toUser());
    }

    @Override
    public List<UserDTO> getUsers(int from, int to) {
        List<User> users = userFacade.findRange(new int[]{from,to});
        List<UserDTO> dto = new ArrayList<UserDTO>();
        for(User u : users)dto.add(new UserDTO(u));
        return dto;
    }

    @Override
    public List<UserDTO> getAllUsers() {
        List<User> users = userFacade.findAll();
        List<UserDTO> dto = new ArrayList<UserDTO>();
        for(User u : users)dto.add(new UserDTO(u));
        return dto;
    }

    @Override
    public int getUsersCount() {
        return userFacade.count();
    }

    @Override
    public UserDTO getUser(Long id) {
        return new UserDTO(userFacade.find(id));
    }

    @Override
    public UserDTO getUserByLogin(String login) {
        return new UserDTO(userFacade.findUserByLogin(login));
    }

    @Override
    public List<UserRolesDTO> getUsersRoles(UserDTO user) {
        List<UserRoles> users = userFacade.getUsersRoles(user.toUser());
        List<UserRolesDTO> dto = new ArrayList<UserRolesDTO>();
        for(UserRoles u : users)dto.add(new UserRolesDTO(u));
        return dto;
    }

    @Override
    public void updateUsersRoles(List<UserRolesDTO> roleList) {
        List<UserRoles> roles = new ArrayList<UserRoles>();
        for(UserRolesDTO u : roleList)roles.add(u.toUserRoles());
        userFacade.editRoles(roles);
    }
    
    @Override
    public List<RoleDTO> findRolesDef(){
        List<Role> roles = userFacade.findRolesDef();
        List<RoleDTO> dto = new ArrayList<RoleDTO>();
        for(Role u : roles)dto.add(new RoleDTO(u));
        return dto;
    }
}
